package com.families.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.families.service.impl.BASE64DecodedMultipartFile;

import sun.misc.BASE64Decoder;

public class FileUtil {
	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
	/**
	 * 图片上传
	 * @param file 文件
	 * @param systemAddress
	 * @return
	 * @throws Exception
	 */
	public static String uploadFile(MultipartFile file,String systemAddress) throws Exception{
		String filename = file.getOriginalFilename();
		//System.out.println(filename)
		//UUID文件名
		String pagename=UUID.randomUUID().toString();
		//获取后缀名
		String suffixname = filename.substring(filename.lastIndexOf("."));
		//判断文件路径是否存在
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String  datapath= dateFormat.format(new Date());
		String uploadpath=systemAddress+"/"+datapath+"/"+pagename+suffixname;
		File wj=new File(uploadpath);

		if (!wj.getParentFile().exists()) {
			wj.getParentFile().mkdirs();
		}
		file.transferTo(wj);
		return "/"+datapath+"/"+pagename+suffixname;
	}
	/**
	 * 判断文件是否为图片
	 * @param file
	 * @return
	 */
	public static boolean isImage(File file) {
		if (!file.exists()) {
			return false;
		}
		BufferedImage image = null;
		try {
			image = ImageIO.read(file);
			if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
				return false;
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 根据文件路劲展示图片
	 * @param path
	 * @param response
	 * @throws Exception
	 */
	public static void showImage(String path, ServletResponse response) throws Exception{
		FileInputStream fis=null;
		OutputStream os=null;
		try {
			response.setContentType("text/html; charset=UTF-8");
			response.setContentType("image/jpeg");
			fis = new FileInputStream(path);
			os =response.getOutputStream();
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = fis.read(buffer)) != -1)
				os.write(buffer, 0, count);
			os.flush();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
		}
	}
	
	public static void downloadFile(HttpServletResponse response, String realPath, String filename,HttpServletRequest request) throws IOException {
		File file = new File(realPath);

		if (file.exists()) {
			response.setContentType("application/force-download");// 设置强制下载不打开
			try { 
				//response.setHeader("Content-Disposition", "attachment; filename=" +java.net.URLEncoder.encode(filename, "UTF-8"));
				//response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("utf-8"),"ISO-8859-1"));
				String userAgent = request.getHeader("User-Agent").toLowerCase();
               
				if (userAgent.indexOf("msie") >0 || userAgent.contains("trident") || userAgent.indexOf("edge")>0){

					filename = URLEncoder.encode(filename, "UTF-8");//IE浏览器

				}else {

					filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");

				} 
				response.setHeader("Content-Disposition", "attachment;filename="+filename);
				response.setContentLengthLong(file.length());

			} catch (UnsupportedEncodingException e1) { 
				// TODO Auto-generated catch
				logger.error("电子保单下载：名字转码异常",e1); 
			}
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}

			} catch (Exception e) {
                logger.error("电子保单下载异常：",e);
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						logger.error("电子保单下载关流异常",e);
					}

				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						logger.error("电子保单下载关流异常",e);
					}

				}
			}
		}else{
			logger.error("文件不存在:{}",realPath);
			//这句话的意思，是让浏览器用utf8来解析返回的数据
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			//这句话的意思，是告诉servlet用UTF-8转码，而不是用默认的ISO8859
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write("文件不存在");
		}
	}
	
	public static MultipartFile base64ToMultipart(String base64) {
		try {
			String[] baseStr = base64.split(",");

			BASE64Decoder decoder = new BASE64Decoder();
			byte[] b = new byte[0];
			b = decoder.decodeBuffer(baseStr[1]);

			for(int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}

			return new BASE64DecodedMultipartFile(b, baseStr[0]);
		} catch (IOException e) {
			return null;
		}
	}
	
}
